package com.yy.controller;

import com.yy.myconfig.LoadBalancer;
import com.yy.entity.Payment;
import com.yy.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author young
 * @date 2022/12/16 15:46
 * @description: 模拟客户端接口
 */
@RestController
@Slf4j
@RequestMapping("order")
public class OrderController {
    /**
     * 当服务为集群时不能将路径写死
     */
   // public static final String PAYMENT_URL="http://localhost:8001";
    /**
     * 用应用名代替
     */
    public static final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE";
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;
    @Resource
    private DiscoveryClient discoveryClient;
    @GetMapping("/add")
    public Result<Payment> create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/add",payment,Result.class);
    }
    @GetMapping("/get/{id}")
    public Result<Payment> create(@PathVariable Integer id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/"+id,Result.class);
    }
    
    @GetMapping("/myTest/lb")
    public String getMyLB(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances==null||instances.size()<=0){
            return null;
        }
        
        ServiceInstance instance = loadBalancer.instance(instances);
        return restTemplate.getForObject(instance.getUri()+"/payment/client/lb",String.class);
    }
}
